package org.pointex.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;


public class StringUtil {
	
	/**
	 * �� object תΪ string
	 * ��� object Ϊ null �򷵻� null
	 * @param obj
	 * @return
	 */
	public static String tryParse(Object obj){
		return tryParse(obj, null);
	}
	
	/**
	 * �� object תΪ string
	 * ��� object Ϊnull�򷵻� defaultString
	 * @param obj
	 * @param defaultString
	 * @return
	 */
	public static String tryParse(Object obj,String defaultString){
		if(obj == null)
		{
			return defaultString;
		}
		return (String)obj;
	}
	
	/**
	 * ��֤һ���ַ����Ƿ�Ϊnull��""
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str){
		return str == null || "".equals(str);
	}
	
	/**
	 * �ж������ַ������ڵĲ�ֵ
	 * */
	public static Integer daysBetween(String dateStr1,String dateStr2) throws ParseException     
    {   
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = sdf.parse(dateStr1);
		Date date2 = sdf.parse(dateStr2);
        Calendar cal = Calendar.getInstance();     
        cal.setTime(date1);     
        long time1 = cal.getTimeInMillis();                  
        cal.setTime(date2);     
        long time2 = cal.getTimeInMillis();          
        long between_days=(time2-time1)/(1000*3600*24);     
             
       return Integer.parseInt(String.valueOf(between_days));            
    }    
	
	 public static int compare_date(String DATE1, String DATE2) {
	        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	        try {
	            Date dt1 = df.parse(DATE1);
	            Date dt2 = df.parse(DATE2);
	            if (dt1.getTime() > dt2.getTime()) {
	                return 1;
	            } else if (dt1.getTime() < dt2.getTime()) {
	                return -1;
	            } else {
	                return 0;
	            }
	        } catch (Exception exception) {
	            exception.printStackTrace();
	        }
	        return 0;
	    }
	
	public static String newToken(HttpServletRequest request){
		Object tokenString = request.getSession(false).getAttribute("token");
	    while (tokenString == null)
	    {
	      tokenString = UUID.randomUUID().toString();
	      request.getSession(false).setAttribute("token", tokenString);
	    }
	    return tokenString.toString();
	}
	
	public static String formatNow() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String now = sdf.format(new Date());
		return now;
	}
	
}
